package com.teddy.model.skos;

import java.util.ArrayList;
import java.util.List;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.ResIterator;
import com.hp.hpl.jena.rdf.model.Resource;

public class DCModel {
	private Model model;
	private String URI;
	
	public DCModel(Model model, String URI){
		this.model = model;
		this.URI = URI;
	}
	
	public String getTitle(){
		NodeIterator it = model.listObjectsOfProperty(DC.title);
		String title = it.next().asNode().getLiteralLexicalForm();
		return title;
	}
	
	public String getSelectedLanguage(){
		NodeIterator it = model.listObjectsOfProperty(DC.title);
		String language = it.next().asNode().getLiteralLanguage();
		return language;
	}
	
	public void setSimpleListeralValue(Property p, String str){
		ResIterator it = model.listSubjectsWithProperty(p);
		
		Resource r = null;
	
		while(it.hasNext()){
			r = it.next();
			model.remove(r.listProperties(p));
		}
		if (r!= null)
			model.addLiteral(r, p, str);
		else{
			model.addLiteral(model.getResource(p.getURI()), p, str);
		}
	}
	
	public String getSimpleLiteralValue(Property p){
		try{
			NodeIterator it = model.listObjectsOfProperty(p);
			return it.next().asNode().getLiteralLexicalForm();
			}
			catch(Exception ex){
				return "";
			}
	}

	public List<String> getLanguages(){
		ArrayList<String> list = new ArrayList<String>();
		NodeIterator it = model.listObjectsOfProperty(DC.language);
		while(it.hasNext()){
			list.add(it.next().asNode().getLiteralLexicalForm());
		}
		return list;
	}
	
	public List<String> getSubjects(){
		ArrayList<String> list = new ArrayList<String>();
		NodeIterator it = model.listObjectsOfProperty(DC.subject);
		while(it.hasNext()){
			list.add(it.next().asNode().getLiteralLexicalForm());
		}
		return list;
	}
	
	public void setURI(String uRI) {
		URI = uRI;
	}

	public String getURI() {
		return URI;
	}

	public void setModel(Model model) {
		this.model = model;
	}

	public Model getModel() {
		return model;
	}
	
	public void removeProperty(Property p, String value){
		ResIterator it = model.listSubjectsWithProperty(p, value);//.listObjectsOfProperty(p);
		
		while (it.hasNext()){
				it.next().removeAll(p);
			}
	}
	
	public void addProperty(Property p, String value, boolean isResource){
		if (! isResource)
			model.getResource(p.getURI()).addLiteral(p, value);
		else
			model.getResource(p.getURI()).addProperty(p, model.getResource(value));
	}
}
